#Include "Protheus.ch"
#Include "TopConn.ch"

User Function AtulChave()

Processa({|| Atualiza()}, "Aguarde", "Atualizando dados...", .T.)

Return Nil

// -------------------------------------------------------------------------------------- //

Static Function Atualiza()

Local aArea      := GetArea()
Local aSF3Area   := SF3->(GetArea())
Local aSFTArea   := SFT->(GetArea())

Local bCondicao  := {||}
Local cCondicao  := ""
Local cQuery     := ""
Local cAlias     := GetNextAlias()
Local cChaveSF3  := ""
Local cChaveSFT  := ""
Local cDtInicial := "20120801"
Local cDtFinal   := "20120831"

Local nRecCount  := 0

cQuery += " SELECT F1_SERIE, F1_DOC, F1_FORNECE, F1_LOJA, F1_CHVNFE, F1_DTDIGIT" + CRLF
cQuery += " FROM " + RetSqlTab("SF1") + CRLF
cQuery += " WHERE F1_DTDIGIT BETWEEN '" + cDtInicial + "' AND '" + cDtFinal + "'" + CRLF
cQuery += 	" AND F1_CHVNFE > '0'" + CRLF
cQuery += 	" AND " + RetSqlDel("SF1") + CRLF
cQuery += 	" AND " + RetSqlFil("SF1") + CRLF
cQuery += " ORDER BY F1_DTDIGIT, F1_SERIE, F1_DOC, F1_FORNECE, F1_LOJA"

TCQUERY cQuery NEW ALIAS &cAlias

Count To nRecCount

IF nRecCount > 0

	(cAlias)->(dbGoTop())
	ProcRegua(nRecCount)
	
//	dbSelectArea("SF3")
//	SF3->(dbSetOrder(4))    // F3_FILIAL+F3_CLIEFOR+F3_LOJA+F3_NFISCAL+F3_SERIE
	dbSelectArea("SFT")
	SFT->(dbSetOrder(1))    // FT_FILIAL+FT_TIPOMOV+FT_SERIE+FT_NFISCAL+FT_CLIEFOR+FT_LOJA+FT_ITEM+FT_PRODUTO
	
	While !(cAlias)->(Eof())

		IncProc()
/*	
		IF SF3->(dbSeek(xFilial("SF3") + (cAlias)->F1_FORNECE + (cAlias)->F1_LOJA + (cAlias)->F1_DOC + (cAlias)->F1_SERIE))
		
			cChaveSF3 := SF3->F3_SERIE + SF3->F3_NFISCAL + SF3->F3_CLIEFOR + SF3->F3_LOJA
		
			While !SF3->(Eof()) .And. cChaveSF3 == (SF3->F3_SERIE + SF3->F3_NFISCAL + SF3->F3_CLIEFOR + SF3->F3_LOJA)
			
 //				IF Empty(SF3->F3_CHVNFE)
			
					RecLock("SF3", .F.)
						SF3->F3_CHVNFE  := (cAlias)->F1_CHVNFE
					MsUnlock()
				
//				EndIF
			
				SF3->(dbSkip())
*/				
		IF SFT->(dbSeek(xFilial("SFT") + "E" + (cAlias)->F1_SERIE + (cAlias)->F1_DOC + (cAlias)->F1_FORNECE + (cAlias)->F1_LOJA))
		
			cChaveSFT := SFT->FT_SERIE + SFT->FT_NFISCAL + SFT->FT_CLIEFOR + SFT->FT_LOJA
		
			While !SFT->(Eof()) .And. cChaveSFT == (SFT->FT_SERIE + SFT->FT_NFISCAL + SFT->FT_CLIEFOR + SFT->FT_LOJA)
			
 //				IF Empty(SFT->FT_CHVNFE)
			
					RecLock("SFT", .F.)
						SFT->FT_CHVNFE  := (cAlias)->F1_CHVNFE
					MsUnlock()
				
//				EndIF
			
				SFT->(dbSkip())
			
			EndDo
		
		EndIF
		
		(cAlias)->(dbSkip())
	
	EndDo
	
EndIF

//SF3->(dbCloseArea())
SFT->(dbCloseArea())

RestArea(aArea)
RestArea(aSF3Area)
RestArea(aSFTArea)

Return Nil